<template>
  <ContentCard>
    <template #header>
      <PageHeaderNew
        title="修改合同"
        showBack
        emitBack
        @back="
          () => {
            router.back();
          }
        "
      />
    </template>
    <div class="tab">
      <div class="title">选择合同与附件：</div>
      <a-space>
        <a-button
          v-for="(item, index) in formData.children"
          :key="item.uuid"
          size="mini"
          class="butss"
          :status="choiceIndex === index ? 'success' : 'normal'"
          shape="round"
          @click="choiceIndex = index"
        >
          {{ item.name }}
        </a-button>
      </a-space>
    </div>
    <RichTextTemplate
      v-if="formData.children"
      v-model:codes="richTextTemplateValue.codes"
      v-model:text="richTextTemplateValue.text"
    />
    <footer>
      <a-space>
        <a-button class="btn" type="primary" @click="save()">
          提交合同
        </a-button>
      </a-space>
    </footer>
  </ContentCard>
</template>

<script setup lang="ts">
import {
  GetUserContractByStatusDetail,
  EditContractFile
} from '@/apis/management/contract/contractManagement/waitSigned';
import { contractStatusToUserStatus } from '@/utils/dictionary/contract';
let router = useRouter();

let choiceIndex = ref(0);
let formData = reactive<any>({});

let save = async () => {
  await Promise.all(
    formData.children.map((item: any) => EditContractFile(item))
  );
  router.back();
  router.back();
};

let richTextTemplateValue = computed({
  get() {
    if (!formData.children || formData.children.length === 0)
      return { text: '', codes: '' };
    return formData.children[choiceIndex.value];
  },
  set(data) {
    if (!formData.children || formData.children.length === 0) return;
    formData.children[choiceIndex.value] = { ...data };
  }
});

let loadData = async () => {
  let data = JSON.parse(localStorage.getItem('contractDetailsData') + '');
  let status =
    contractStatusToUserStatus.find(
      ({ value }) => value === data.contractStatus
    )?.status || 0;
  let res = await GetUserContractByStatusDetail({
    userId: data.id,
    status: status
  });
  if (!res[0]) return;
  Object.assign(formData, res[0]);
};
loadData();
</script>

<style scoped>
footer {
  height: 50px;
  padding-top: 15px;
  width: calc(100% - 220px);
  background-color: #fff;
  box-shadow: 1px -1px 10px 0 #cacaca;
  position: fixed;
  bottom: 0;
  left: 221px;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  z-index: 1000;
}
.tab {
  display: flex;
  justify-content: left;
  align-items: center;
  height: 25px;
  margin-bottom: 10px;
  .title {
    font-size: 16px;
    margin-right: 10px;
  }
}
</style>
